<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Cookie;
use think\Request;
use app\index\model\Course;
use app\index\model\KnowUser;

class Other extends Common
{
	private $wx_appid = 'wx8f55d70da457e929';
	private $wx_appsecret = '3860b146c323eb30a684533d01c7591f';

	public function about(){
		return $this->fetch();
	}

	public function zhangyupeng(){
		return $this->fetch();
	}

	public function yangshujuan(){
		return $this->fetch();
	}

	public function shiyaping(){
		return $this->fetch();
	}

	public function return(){
		return $this->fetch();
	}

	public function wechat(){
		if($_GET['code']){
			self::wechat_oauth();
		}else{
			$this->redirect('https://open.weixin.qq.com/connect/qrconnect?appid='. $this->wx_appid .'&redirect_uri=https://www.atxunda.com/third/wechat.html&response_type=code&scope=snsapi_login&state=' . md5 ( uniqid ( rand (), true ) ) . '#wechat_redirect');
		}
	}

	private function get_wechat_access_token( $code = null ){
		$code = $code ? $code : $_GET['code'];
		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->wx_appid . '&secret=' . $this->wx_appsecret . '&code=' . $code . '&grant_type=authorization_code';
		return json_decode(file_get_contents($url),true);
	}

	private function wechat_oauth(){
		if(!isset($_GET['code'])) $this->error('code empty.');
		$code = $_GET['code'];
		$json_token = self::get_wechat_access_token( $code );
		$info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $json_token['access_token'] . '&openid=' . $json_token['openid'];
		$user_info = json_decode(file_get_contents($info_url),true);
		$third = Db::table('know_user_third')->where(['openid'=>$user_info['unionid']])->find();
		if($third){
			Db::table('know_user_third')->where(['openid'=>$user_info['unionid']])->update(['last_time'=>time()]);
			if($third['user_id']){
				$status = 'login';
				$data = KnowUser::field('know_phone,know_email')->where(['know_user_id'=>$third['user_id']])->find();
				$phone = $data['know_phone'] ? $data['know_phone'] : $data['know_email'];
				KnowUser::updateUser($phone);
			}else{
				$status = 'nouser';
				Cookie::set('login_wechat',$user_info['unionid']);
			}
		}else{
			$status = 'nouser';
			$third = Db::table('know_user_third')->insert([
				'openid' => $user_info['unionid'],
				'start_time' => time(),
				'last_time' => time(),
				'nickname' => $user_info['nickname'],
			]);
			Cookie::set('login_wechat',$user_info['unionid']);
		}
		if($status == 'login'){
			echo '<script type="text/javascript">
				var redirect = getUrlParam("redirect");
				if(!redirect) redirect = "/";
				top.location.href = redirect;
				function getUrlParam(name) {   
					var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
					var r = top.location.search.substr(1).match(reg);
					if (r != null) return unescape(r[2]); return null;
				}
			</script>';
		}else{
			echo '<script type="text/javascript">
				var redirect = getUrlParam("redirect");
				if(!redirect) redirect = "";
				var salt = getUrlParam("salt");
				if(!salt) salt = "";
				top.location.href = "/third/complete?redirect="+redirect+"&salt="+salt;
				function getUrlParam(name) {   
					var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
					var r = top.location.search.substr(1).match(reg);
					if (r != null) return unescape(r[2]); return null;
				}
			</script>';
		}
	}

	public function uploads(Request $request){
		$param = $request->param();
		$path = $param['type'] == 1 ? 'uploads' : 'editoruploads';
		$filename = $param['type'] == 1 ? 'file' : 'editormd-image-file';
		$file = request()->file($filename);
		$data = array();
		if($file){
			// 移动到框架应用根目录/public/editoruploads/ 目录下
			$info = $file->move(ROOT_PATH . 'public' . DS . $path);
			if($info){
				$req['type_logo'] = $info->getSaveName();
				$data['success'] = 1;
				$data['message '] = '上传成功';
				$data['url'] = '/public/'.$path.'/'.$info->getSaveName();
			}else{
				// 上传失败获取错误信息
				echo $file->getError();
				$data['success'] = 0;
				$data['message '] = '上传失败';
			}
		}else{
			$data['success'] = 0;
			$data['message '] = '上传失败';
		}
		return json($data);
	}


	public function ccnotify(Request $request){
		$param = $request->param();
		file_put_contents ( dirname(dirname(dirname(dirname ( __FILE__ )))).'/log.txt', date ( "Y-m-d H:i:s" ) . "  " . var_export($param,true) . "\r\n", FILE_APPEND );
		if ($param) 
		{
			$paramHash = $param['hash'];unset($param['hash']);
			$sign = '';
			foreach ($param as $key => $val) {
				$sign .= $key . '=' . urlencode($val) . '&';
			}
			$salt = $sign.'salt=SexXFIDnvcWf0oXvrLp3LlsGjCHQA8DX';
			$hash = md5($salt);
			$data = Course::where('vid',$param['videoid'])->find();
			if (strtoupper($hash) == $paramHash && $data) 
			{
				if($param['status'] == "OK") 
				{
					$canshu = [
						'userid' => '2CF6808DAEF7DA69',
						'format' => 'json',
						'httpsflag' => 1,
						'videoid' => $param['videoid'],
						'authtimeout' => 60*60*24*365*5
					];
					list($result, $status, $message) = ccTHQS($canshu, 'http://union.bokecc.com/api/audio');
					Course::where('vid',$param['videoid'])->update([
						'video_time' => $param['duration'],
					]);
				}
			}
		}
	}
}